import json
from datetime import datetime
import requests
import time
from flask import Flask, render_template

# -------------------------------------获取cookie------formatted_cookies------
def get_datacenter_1haolou_data():

    current_timestamp = int(time.time()) * 1000  # 获取当前时间戳（毫秒级）,每个请求都有唯一的时间标记
    url = 'https://x.x.x.x:31943/login/authenticate.action'
    params = {'_': current_timestamp}#将当前时间戳作为参数添加到请求中
    #登录请求的表单数据，包括用户名，密码，
    data = {
        'username': 'xxxxxxxxxxxxxxxxxxxx',
        'value': 'xxxxxxxxxxxxxxxxxxx',
        'vcode': '',
        'isEncrypt': 'false'
    }
    #禁用SSL证书验证警告，用于在测试环境中忽略SSL证书验证。
    requests.packages.urllib3.disable_warnings()
    #发送HTTP POST请求，包含URL、参数、表单数据，并禁用SSL证书验证。响应存储在变量
    response = requests.post(url, params=params, data=data, verify=False)  # verify=False忽略SSL证书验证，仅限于测试环境
    #初始化一个变量，用于存储格式化后的Cookie信息
    formatted_cookies = ''
    if response.status_code == 200:
        data = response.json()
        cookies = response.cookies  # 获取响应中的Cookie信息
        # 将获取到的Cookie信息格式化为字符串，以便后续使用
        formatted_cookies = '; '.join([f"{cookie.name}={cookie.value}" for cookie in cookies])
        # print(formatted_cookies)
    else:
        #如果请求失败，输出失败的状态码。
        print("请求失败:", response.status_code)

    # ---------------------------开始请求参数---温度湿度数据--------------------------------

    url = "https://10.106.134.15:31943/rest/view/topo/3D/getSensorTemperatueData"

    params = {
        "dn": "NE=33554536",
        "_": current_timestamp  # 使用动态获取的当前时间戳
    }

    headers = {
        'Cookie': formatted_cookies
    }
    requests.packages.urllib3.disable_warnings()
    response = requests.get(url, params=params, headers=headers, verify=False)  # 在这个示例中，verify=False绕过SSL证书验证
    if response.status_code == 200:
        data = response.json()
        # 处理响应数据
        humiavg_value = data.get('humiavg')
        humimax_value = data.get('humimax')
        tempavg_value = data.get('tempavg')
        tempmax_value = data.get('tempmax')

        # 设置颜色标记
        humiavg_color = '<span style="color:red;">' if humiavg_value > 50 else '<span style="color:green;">'
        humimax_color = '<span style="color:red;">' if humimax_value > 70 else '<span style="color:green;">'
        tempavg_color = '<span style="color:red;">' if tempavg_value > 25 else '<span style="color:green;">'
        tempmax_color = '<span style="color:red;">' if tempmax_value > 26 else '<span style="color:green;">'

        # 构建格式化后的温湿度值字符串
        humiavg_formatted = f'{humiavg_color}{humiavg_value}</span>'
        humimax_formatted = f'{humimax_color}{humimax_value}</span>'
        tempavg_formatted = f'{tempavg_color}{tempavg_value}</span>'
        tempmax_formatted = f'{tempmax_color}{tempmax_value}</span>'

    else:
        print("请求失败:", response.status_code)
    # ------------------------Roarand-----------------------------------------
    current_timestamp = int(time.time()) * 1000
    url = "https://10.106.134.15:31943/rest/framework/random"
    params = {
        "_": current_timestamp  # 使用动态获取的当前时间戳
    }
    headers = {
        'Cookie': formatted_cookies
    }
    response = requests.get(url, data=data, headers=headers, verify=False)  # 使用 data 参数传递表单数据
    text_roaRand = ''
    if response.status_code == 200:
        text_roaRand = response.text  # 获取响应内容的文本形式
        print(text_roaRand)
    else:
        print("请求失败:", response.status_code)

    #----------------------------获取modelid-------------------
    url = 'https://10.106.134.15:31943/rest/fm/roa/entry'

    headers = {
        "Cookie": formatted_cookies,
        'Host': '10.106.134.15:31943',
        'Origin': 'https://10.106.134.15:31943',
        'Referer': 'https://10.106.134.15:31943/fm/alarmview/current/currentAlarmView.html?dn=NE%3D33554536&cleared=false',
        'Roarand': text_roaRand
    }
    data = {
        'command.url': 'current.alarm.executor',
        'command.id': 'init.page',
        'command.param': '{"dn":"NE=33554536","cleared":"false"}'
    }
    requests.packages.urllib3.disable_warnings()
    response = requests.post(url, data=data, headers=headers, verify=False)  # 在这个示例中，verify=False绕过SSL证书验证
    ModeID = ''
    if response.status_code == 200:
        data = response.json()
        ModeID = data["content"]["modelID"]
    else:
        print("请求失败:", response.status_code)
    # -----------------------预准备数据阶段----------------------------
    url='https://10.106.134.15:31943/rest/fm/roa/restrict/entry'
    data={
        'command.url':'current.alarm.executor',
        'command.id':'query.data',
        'command.param':'{"clearedStatus":"0","customFilters":{},"moDnList":["NE=33554536"]}',
        'command.modelID':ModeID,
        'command.dateformat':'yyyy-MM-dd'
    }

    headers = {
        'Cookie': formatted_cookies,
        'Referer':'https://10.106.134.15:31943/fm/alarmview/current/currentAlarmView.html?dn=NE%3D33554536&cleared=false',
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, br, zstd',
        'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
        'Pragma':'no-cache',
        'Roarand':text_roaRand,
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Host':'10.106.134.15:31943',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
        'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"'
    }
    requests.packages.urllib3.disable_warnings()
    response = requests.post(url, data=data, headers=headers, verify=False)  # 在这个示例中，verify=False绕过SSL证书验证
    if response.status_code == 200:
        data = response.json()
        print(data)

    # -----------------------获取告警信息(1-2)------------------------------
    url = "https://10.106.134.15:31943/rest/fm/currentAlarm"

    # 获取当前时间
    current_time = datetime.now()

    # 转换为毫秒级时间戳
    timestamp_milliseconds1_2 = int(current_time.timestamp() * 1000)
    params = {
        '_': timestamp_milliseconds1_2,  # 使用动态获取的当前时间戳
        'operCondition.queryType': 1,
        'operCondition.operType': 1,
        'operCondition.from': 1,
        'operCondition.to': 2,
        'operCondition.topoStart': 'stopped',
        'operCondition.modelID': ModeID,
        'operCondition.firstlogSN': 0
    }

    headers = {
        'Cookie': formatted_cookies,
        'Referer':'https://10.106.134.15:31943/fm/alarmview/current/currentAlarmView.html?dn=NE%3D33554536&cleared=false',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding': 'gzip, deflate, br, zstd',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Host':'10.106.134.15:31943',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest',
        'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"'
    }
    requests.packages.urllib3.disable_warnings()
    response = requests.get(url, params=params, headers=headers, verify=False)  # 在这个示例中，verify=False绕过SSL证书验证

    # 检查API请求是否成功
    combined_string = ''
    if response.status_code == 200:
        # 解析JSON响应
        data_str = response.text
        data = json.loads(data_str)
        # print(data)
        # 提取dataObject列表
        data_objects = data.get('dataObject', [])

        for data_object in data_objects:
            # 提取字段的中文值
            event_time = data_object.get('eventTime', 'N/A')
            alarm_name = data_object.get('alarmName', 'N/A')
            detailed_information = data_object.get('detailedInformation', 'N/A')
            alarm_name_display = data_object.get('alarmNameDisplay', 'N/A')
            obj_ins_display = data_object.get('objInsDisplay', 'N/A')

            # 拼接成一个字符串
            combined_string = f"事件时间: {event_time}, 告警名称: {alarm_name}, 详细信息: {detailed_information}, " \
                              f"告警名称显示: {alarm_name_display}, 对象实例显示: {obj_ins_display}"
            # 打印拼接后的字符串
            print(combined_string)
            print("-----------")
    else:
        print("请求失败，状态码:", response.status_code)

    # --------------------------------A模块ups电池后备时间---------------------------------
    url = 'https://10.106.134.15:31943/rest/view/keydevice/ups'

    params = {
        "dn": "NE=33554546.40978-23041",
        "_": current_timestamp  # 使用动态获取的当前时间戳
    }
    headers = {
        'Cookie': formatted_cookies
    }
    requests.packages.urllib3.disable_warnings()
    response = requests.get(url, params=params, headers=headers, verify=False)  # 在这个示例中，verify=False绕过SSL证书验证
    if response.status_code == 200:
        data = response.json()

        # 查看整个 JSON 响应
        # print(data)

        # 获取 "top" 部分的信息
        top_info = data.get("top")
        if top_info and len(top_info) >= 2:  # 确保至少有两个条目
            second_last_entry = top_info[-2]  # 倒数第二项
            last_entry = top_info[-1]  # 倒数第一项
            second_last_value = second_last_entry.get("counterValue")
            last_value = last_entry.get("counterValue")



            print("A模块供电状态:", second_last_value)
            print("ups供电时间:", last_value, "分钟")
    else:
        print("请求失败:", response.status_code)

    # --------------------------------B模块ups状态----------------------------
    url = 'https://10.106.134.15:31943/rest/view/keydevice/ups'

    params = {
        "dn": "NE=33554543.40978-4113",
        "_": current_timestamp  # 使用动态获取的当前时间戳
    }
    headers = {
        'Cookie': formatted_cookies
    }
    requests.packages.urllib3.disable_warnings()
    response = requests.get(url, params=params, headers=headers, verify=False)  # 在这个示例中，verify=False绕过SSL证书验证
    if response.status_code == 200:
        dataB = response.json()

        # 查看整个 JSON 响应
        # print(dataB)

        # 获取 "top" 部分的信息
        B_top_info = dataB.get("top")
        if B_top_info and len(B_top_info) >= 2:  # 确保至少有两个条目
            Bsecond_last_entry = B_top_info[-2]  # 倒数第二项
            Blast_entry = B_top_info[-1]  # 倒数第一项

            B_UPS_status = Bsecond_last_entry.get("counterValue")
            B_time_value = Blast_entry.get("counterValue")

            print("B模块供电状态:", B_UPS_status)
            print("ups供电时间:", B_time_value, "分钟")
    else:
        print("请求失败:", response.status_code)
    return {
        'humiavg_value': humiavg_value,
        'humimax_value': humimax_value,
        'tempavg_value': tempavg_value,
        'tempmax_value': tempmax_value,
        'combined_string': combined_string,
        'second_last_value': second_last_value,
        'last_value': last_value,
        'B_UPS_status': B_UPS_status,
        'B_time_value': B_time_value,
    }
get_datacenter_1haolou_data()
